package org.acsis.jee.dao.hibernate;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import org.acsis.jee.dao.Dao;
import org.hibernate.HibernateException;
import org.hibernate.Session;

public abstract class BasicHibernateDAO<T, PK extends Serializable> implements Dao<T, PK>{

	protected Session session;
	
	public void setSession(Session session) {
		this.session = session;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public PK create(T t) {
		return (PK) session.save(t);
	}

	@Override
	public boolean delete(T t) {
		
		try{
			session.delete(t);
		}
		catch (HibernateException e) {
			return false;
		}
		
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public T get(PK id) {
		return (T) session.get(getPersistantClassType(), id);
	}

	@Override
	public boolean update(T t) {
		
		try{
			session.update(t);
		}
		catch (HibernateException e) {
			return false;
		}
		
		return true;
	}
	
	@SuppressWarnings("unchecked")
	private Class<T> getPersistantClassType(){
		return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}

}
